package com.tom.myjni.fmpeg;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;

import com.tom.myjni.R;

import java.io.File;

import com.tbruyelle.rxpermissions2.RxPermissions;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class CompressVideoActivity extends AppCompatActivity {

    private File mInFile = new File(Environment.getExternalStorageDirectory(), "test.mp4");
    private File mOutFile = new File(Environment.getExternalStorageDirectory(), "out.mp4");


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compress_video);
        // ffmpeg 处理视频： ffmpeg -i test.mp4 -b:v 1024k out.mp4
    }

    public void compressVideo(View view) {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) { // 给了相关权限
                            compressVideo();
                        }
                    }
                });
    }

    private void compressVideo() {
        String[] compressCommand = {"ffmpeg", "-i", mInFile.getAbsolutePath(), "-b:v", "1024k", mOutFile.getAbsolutePath()};
        Log.e("TAG", "压缩开始：compressVideo");

        Observable.just(compressCommand)
                .map(new Function<String[], File>() {
                    @Override
                    public File apply(String[] compressCommand) throws Exception {
                        // 压缩是耗时的，子线程，处理权限
                        VideoCompress videoCompress = new VideoCompress();
                        videoCompress.compressVideo(compressCommand, new VideoCompress.CompressCallback() {
                            @Override
                            public void onCompress(int current, int total) {
                                Log.e("TAG", "压缩进度：" + current + "/" + total);
                            }
                        });
                        return mOutFile;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<File>() {
                    @Override
                    public void accept(File file) throws Exception {
                        // 压缩完成
                        Log.e("TAG", "压缩完成：" + file.getAbsolutePath());
                    }
                });
    }

}